<?php

namespace App\Http\Middleware;

use App\Exceptions\BusinessException;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;

class CheckPermission
{
    /**
     * @author moell<moel91@foxmail.com>
     * @param $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, \Closure $next)
    {
        $permission = Route::currentRouteName();

        if ($permission && !$this->checkPermission($permission)) {
            throw new BusinessException('未授权',403);
        }

        return $next($request);
    }

    public function checkPermission($permission){
        $user = Auth::user();
        $perms = $user->roles()->with(['menus'=>function($q){
            $q->where('visible',1)->whereIn('type',['BUTTON']);
        }])->get()->pluck('menus')->flatten()->unique()->pluck('perm')->unique()->toarray();
        if(in_array($permission, $perms, true)){
            return true;
        }
        return false;
    }
}
